package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.notice;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.config.SzConfig;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysFiles;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysUser;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.TNotice;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.NoticeExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysFilesService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ITNoticeService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.Constructor.TNotice2GetNoticeVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetNoticeVo;
import com.xiaoxu.intranetweb.util.FileUploadUtils;
import com.xiaoxu.intranetweb.util.SzResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Future;

@Component
public class NoticeBu {
    @Autowired
    private ITNoticeService itNoticeService;
    @Autowired
    private ISysFilesService fileBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private TNotice2GetNoticeVo tNotice2GetNoticeVo;

    //查询通告
    public SzResult getNotice(String  page,String pageSize,String title,String startTime,String endTime,String token,String plantId) throws Exception {
        Page<TNotice> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
        ArrayList<GetNoticeVo> getNoticeVos = new ArrayList<>();
        QueryWrapper<TNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("ID", "N_TITLE","N_SHORT_CONTENT", "N_CREATETIME", "N_CREATER");
        queryWrapper.eq("DEL_FLAG", 0);
        queryWrapper.like(title != null && !title.equals(""), "N_TITLE", title);
        queryWrapper.eq(plantId != null && !plantId.isEmpty(), "DATA_FROM", plantId);
        queryWrapper.between(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals(""), "N_CREATETIME", startTime, endTime);
        queryWrapper.orderByDesc("N_CREATETIME");
        IPage<TNotice> iPage = itNoticeService.page(page1, queryWrapper);
        //将list集合封装成GetNoticeVo
        for (TNotice tNotice : iPage.getRecords()) {
            GetNoticeVo getNoticeVo = tNotice2GetNoticeVo.tNotice2GetNoticeVo(tNotice);
            QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
            sysFilesQueryWrapper.eq("CONN_ID", getNoticeVo.getId());
            List<SysFiles> fileList = fileBu.list(sysFilesQueryWrapper);
            String createrName = "";
            try {
                if (getNoticeVo.getCreater() != null) {
                    createrName = userInfoDao.getUser(getNoticeVo.getCreater()).getUserName();
                    getNoticeVo.setCreaterName(createrName);
                }
            } catch (Exception e) {
                getNoticeVo.setCreaterName("");
                e.printStackTrace();
            }
            getNoticeVo.setFileList(fileList);
            getNoticeVo.setTotal(fileList.size());
            //查询file List的总数
            getNoticeVos.add(getNoticeVo);
        }
        long total = iPage.getTotal();
        Map map = new HashMap();
        map.put("total", total);
        map.put("list", getNoticeVos);
        return SzResult.success(map);
    }
//查询公告详情
public SzResult getNoticeDetail(String id) {
    QueryWrapper<TNotice> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("ID", id);
    TNotice tNotice = itNoticeService.getOne(queryWrapper);
    GetNoticeVo getNoticeVo = tNotice2GetNoticeVo.tNotice2GetNoticeVo(tNotice);
    QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
    sysFilesQueryWrapper.eq("CONN_ID", getNoticeVo.getId());
    List<SysFiles> fileList = fileBu.list(sysFilesQueryWrapper);
    String createrName = null;
    try {
        createrName = userInfoDao.getUser(getNoticeVo.getCreater()).getTrueName();
    } catch (Exception e) {
        e.printStackTrace();
    }
    getNoticeVo.setCreaterName(createrName);
    getNoticeVo.setFileList(fileList);
    getNoticeVo.setTotal(fileList.size());
    return SzResult.success(getNoticeVo);
}

    //增加通告
    public SzResult addNotice(String title, String content, String shortContent,String token,String plantId) throws Exception {
        LocalDateTime creatTime = LocalDateTime.now();
        TNotice tNotice = new TNotice();
        tNotice.setNCreatetime(creatTime);
        tNotice.setDelFlag(0);
        if (title != null && !title.equals("")) {
            tNotice.setNTitle(title);
        }
        if (content != null && !content.equals("")) {
            tNotice.setNContent(content);
        }
        if (shortContent != null && !shortContent.equals("")) {
            tNotice.setNShortContent(shortContent);
        }
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId =userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        tNotice.setNCreater(user.getId());
        tNotice.setDataFrom(plantId);
        itNoticeService.save(tNotice);
        String trueName = user.getTrueName();

        sysLogBu.logRecord("新增公告", trueName, "新增了标题为" + title + "的公告",plantId);
        return SzResult.Success();
    }
    //删除通告
    public SzResult delNotice(String id,String token,String plantId) throws Exception {
        QueryWrapper<TNotice> tNoticeQueryWrapper = new QueryWrapper<>();
        tNoticeQueryWrapper.eq("ID", id);
        TNotice tNotice = itNoticeService.getOne(tNoticeQueryWrapper);
        Integer delFlag = tNotice.getDelFlag();
        if (delFlag == 1) {
            return SzResult.error("该通告已被删除");
        }
        String title = tNotice.getNTitle();
        //将删除标志改为1
        tNotice.setDelFlag(1);
        itNoticeService.updateById(tNotice);
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        String trueName = user.getTrueName();
        sysLogBu.logRecord("删除公告", trueName, "删除了标题为" + title + "的通告信息", plantId);
        return SzResult.Success();
    }

    //修改通告
    public SzResult updateNotice(String id, String title, String content, String shortContent, String creater,String token,String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<TNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TNotice tNotice = itNoticeService.getOne(queryWrapper);
//        StringBuilder logMsg = new StringBuilder();
        if (title != null && !title.equals("")) {
            tNotice.setNTitle(title);
        }else{
            return SzResult.error("标题不能为空");
        }
            tNotice.setNContent(content);

            tNotice.setNShortContent(shortContent);
            tNotice.setNCreater(user.getId());
        itNoticeService.updateById(tNotice);
        String trueName = user.getTrueName();
        sysLogBu.logRecord("修改公告", trueName, "修改了标题为" + title + "的公告信息", plantId);
        return SzResult.Success();
    }
//    上传文件
    public SzResult uploadFile(MultipartFile file, String connId,String token) throws Exception {
        //存储文件返回绝对路径
        String filePath = FileUploadUtils.upload(SzConfig.getUploadPath(),file);
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        SysFiles sysFiles = new SysFiles();
        sysFiles.setConnId(connId);
        sysFiles.setUploadFrom(StpUtil.getLoginIdByToken(token).toString());
        sysFiles.setFileName(fileName);
        sysFiles.setFilePath(filePath);
        sysFiles.setFileSize(String.valueOf(file.getSize()));
        sysFiles.setFileType(suffix.replace(".", ""));
        sysFiles.setUploadTime(LocalDateTime.now());
        fileBu.save(sysFiles);
        return SzResult.success(sysFiles);
    }
//    下载文件
    public SysFiles downloadFile(String id) {
//        根据id区数据库中查询文件信息
        QueryWrapper<SysFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        SysFiles sysFiles = fileBu.getOne(queryWrapper);
        return sysFiles;
    }
//    删除文件
    public  SzResult deleteFile(String id) {
        QueryWrapper<SysFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        SysFiles sysFiles = fileBu.getOne(queryWrapper);
        String filePath = sysFiles.getFilePath();
        String fileType = sysFiles.getFileType();
        File file = new File(filePath +sysFiles.getId()+"."+fileType);
        if (file.exists()) {
            file.delete();
        }
        fileBu.removeById(id);
        return SzResult.Success();
    }
//    文件预览
    public Path previewFile(String id) {
        QueryWrapper<SysFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        SysFiles sysFiles = fileBu.getOne(queryWrapper);
        //        判断一下sysFiles.getFileType()是否是图片格式
        if (sysFiles.getFileType().equals("jpg") || sysFiles.getFileType().equals("png") || sysFiles.getFileType().equals("gif") || sysFiles.getFileType().equals("jpeg") || sysFiles.getFileType().equals("bmp") || sysFiles.getFileType().equals("webp") || sysFiles.getFileType().equals("svg")){
            String filePath = sysFiles.getFilePath();
            String fileType = sysFiles.getFileType();
            Path path = Paths.get(filePath +sysFiles.getId()+"."+fileType);
            return path;
        } else {
            return null;
        }
    }

    public Future<List<NoticeExcelEn>> exportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, Boolean isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String plantId, String title) {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<NoticeExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        NoticeExcelEn noticeExcelEn = NoticeExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("title")) {
                                if (entry.getValue() != null) {
                                    noticeExcelEn.setTitle(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("shortContent")) {
                                if (entry.getValue() != null) {
                                    noticeExcelEn.setShortContent(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("creatTime")) {
                                if (entry.getValue() != null) {
                                    noticeExcelEn.setCreatTime(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(noticeExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<TNotice> queryWrapper = new QueryWrapper<>();
                    queryWrapper.like(title != null && !title.equals(""), "N_TITLE", title);
                    queryWrapper.eq("DEL_FLAG", 0);
                    queryWrapper.eq("DATA_FROM", plantId);
                    List<TNotice> tNotices = itNoticeService.list(queryWrapper);
                    for (TNotice tNotice : tNotices) {
                        NoticeExcelEn noticeExcelEn = NoticeExcelEn.builder()
                                .title(Optional.ofNullable(tNotice.getNTitle()).orElse(""))
                                .shortContent(Optional.ofNullable(tNotice.getNShortContent()).map(Object::toString).orElse(""))
                                .creatTime(Optional.ofNullable(tNotice.getNCreatetime()).map(Object::toString).orElse(""))
                                .build();
                        list.add(noticeExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        NoticeExcelEn noticeExcelEn = NoticeExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("title")) {
                                if (entry.getValue() != null) {
                                    noticeExcelEn.setTitle(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("shortContent")) {
                                if (entry.getValue() != null) {
                                    noticeExcelEn.setShortContent(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("creatTime")) {
                                if (entry.getValue() != null) {
                                    noticeExcelEn.setCreatTime(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(noticeExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }
}
